#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace log_ns;
const static u_int16_t defaultport = 8888;
const static int defaultfd = -1;
const static int defaultsize = 1024;
//为了实现解耦合我们继续使用包装器执行回掉函数
//传人文件描述符，信息，以及客户端信息（谁发的
using service_t =std::function<void(int fd,std::string message,InetAddr &who)>;
enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

class UdpServer : public nocopy
{
public:
    UdpServer(service_t func ,uint16_t port = defaultport) :_func(func) , _port(port), _sockfd(defaultfd),_isrunning(false)
    {
    }
    
    void InitServer()
    {
        // 1.创建socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
           LOG(FATAL,"socket error\n");
           exit(SOCKET_ERROR);
        }
        LOG(DEBUG,"socket create success,_sockfd:%d\n",_sockfd);
    
        //2.bind
        struct sockaddr_in local;//struct sockaddr_in 是在 C 和 C++ 网络编程里用于表示 IPv4 地址的结构体
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(_port);
        local.sin_addr.s_addr=INADDR_ANY; //服务器端，进行任意IP地址绑定

        int n=::bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n<0)
        {
            LOG(FATAL,"bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG,"socket bind success\n");
    }
    void Start()
    {
        _isrunning=true;
        char message[1024];
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            ssize_t n=recvfrom(_sockfd,message,sizeof(message)-1,0,(struct sockaddr*)&peer,&len);
            if(n>0)
            {
                InetAddr addr(peer);
                message[n]=0;
                LOG(DEBUG,"[%s]# %s\n",addr.AddrStr().c_str(),message);
                _func(_sockfd,message,addr);
                LOG(DEBUG, "return udpserver\n");

            }
            else{
                std::cout << "recvform , error" << std::endl;
            }
        }
    }
    ~UdpServer()
    {
        if(_sockfd>defaultfd)
        ::close(_sockfd);
    }

private:
    uint16_t _port;
    int _sockfd;  //// 读写都用同一个sockfd， 反应说明：UDP是全双工通信的！
    bool _isrunning;

    service_t _func;
};